package com.example.seed.service;

import com.example.seed.entity.Fetchers;
import com.example.seed.entity.SysDept;
import com.example.seed.entity.Tables;
import org.babyfish.jimmer.spring.repository.JRepository;
import org.babyfish.jimmer.sql.ast.Predicate;
import org.jetbrains.annotations.Nullable;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;


public interface SysDeptRepository extends JRepository<SysDept, Long> {

    /**
     * 全部提取
     *
     * @param sysDeptList 系统部门列表
     * @return {@link Collection}<{@link Long}>
     */
    private static Collection<Long> flatAll(List<SysDept> sysDeptList) {
        return sysDeptList.stream().flatMap(it -> Stream.concat(Stream.of(it.id()), flatAll(it.childNodes()).stream())).collect(Collectors.toSet());
    }


    default Collection<Long> findChildNodeIdsByParentId(@Nullable Long parentId) {
        List<SysDept> deptList = sql().createQuery(Tables.SYS_DEPT_TABLE).where(Predicate.or(Tables.SYS_DEPT_TABLE.parentId().eq(parentId), Tables.SYS_DEPT_TABLE.id().eq(parentId))).select(Tables.SYS_DEPT_TABLE.fetch(Fetchers.SYS_DEPT_FETCHER.recursiveChildNodes())).execute();
        return flatAll(deptList);
    }
}
